/**
 * 入参
 *  持仓可用
 */
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { Spin } from 'antd';
import { FirstHeaderC, NoDataMaskC, IconC, TableC } from '../../../comps';
import { connect } from 'dva';
import { fixedNum, findValueByCode } from '../../../utils/utils';
import myStyle from './style/index.less';

class TradeHoldC extends PureComponent {
  //默认值
  static defaultProps = {
    onChange: () => {},
    codeChangeInfo: () => {}, //双击表单 抛出每行数据
    portfolio: undefined, //组合id
    productGroupId: undefined, //产品组id
    tradingcode: undefined,
    exchangecode: undefined,
    timeStamp: null,
    loading: false,
    width: '100%',
    hasHeader: true,
    type: undefined,
    hkType: '1', // 默认模式1 /2港股通模式/3股指期权
    securityType: undefined, //证券类别
    queryModel:'old',//默认原接口，old;新接口new
  };
  state = {
    availableAmount: '--', //available
    currentAmount: '--', //hold
    masking: true, //是否显示蒙版
    maatApi: false,
    loading: false,
    hold: '--', //t+0
    available: '--', //t+2
    holdData: [], //持仓表格 股指期权
  };

  componentDidMount() {
    const { portfolio, productGroupId, tradingcode, exchangecode, hkType } = this.props;
    if (portfolio && productGroupId) {
      // 如果组合id和产品组id都存在
      if (hkType == '1') {
        // 默认模式
        this.props.onChange({ hold: undefined, available: undefined, investmentType: undefined }); //抛出投资类型
      } else if (hkType == '2') {
        // 港股通模式
        this.props.onChange({
          t0: undefined,
          t2: undefined,
          investmentType: undefined,
        });
      }
    } else {
      if (portfolio && tradingcode && exchangecode) {
        this.getTradeHold(this.props);
      } else if (productGroupId && tradingcode && exchangecode) {
        this.getDataByProductGroupId(this.props);
      } else {
        if (hkType == '1') {
          // 默认模式
          this.props.onChange({ hold: undefined, available: undefined, investmentType: undefined }); //抛出投资类型
        } else if (hkType == '2') {
          // 港股通模式
          this.props.onChange({
            t0: undefined,
            t2: undefined,
            investmentType: undefined,
          });
        }
      }
    }
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    const { portfolio, productGroupId, timeStamp, tradingcode, exchangecode, hkType } = this.props;
    if (
      portfolio !== nextProps.portfolio ||
      tradingcode != nextProps.tradingcode ||
      exchangecode != nextProps.exchangecode ||
      timeStamp !== nextProps.timeStamp ||
      productGroupId !== nextProps.productGroupId
    ) {
      if (nextProps.portfolio && nextProps.productGroupId) {
        // 如果组合id和产品组id都存在
        if (hkType == '1') {
          // 默认模式
          this.setState({
            availableAmount: '--', //available
            currentAmount: '--', //hold
            masking: true,
          });
          this.props.onChange({ hold: undefined, available: undefined, investmentType: undefined }); //抛出投资类型
        } else if (hkType == '2') {
          // 港股通模式
          this.setState({
            hold: '--', //t+0
            available: '--', //t+2
            masking: true,
          });
          this.props.onChange({
            t0: undefined,
            t2: undefined,
            investmentType: undefined,
          });
        }
        this.props.onChange({ hold: undefined, available: undefined, investmentType: undefined }); //抛出投资类型
      } else {
        if (hkType == '3') {
          if (nextProps.portfolio) {
            // 股指期权
            this.getTradeHold(nextProps);
          } else {
            this.props.codeChangeInfo({});
            this.props.onChange([]);
            this.setState({
              holdData: [],
              masking: true,
            });
          }
          return;
        }
        if (nextProps.portfolio && nextProps.tradingcode && nextProps.exchangecode) {
          this.getTradeHold(nextProps);
        } else if (nextProps.productGroupId && nextProps.tradingcode && nextProps.exchangecode) {
          this.getDataByProductGroupId(nextProps);
        } else {
          if (hkType == '1') {
            // 默认模式
            this.setState({
              availableAmount: '--', //available
              currentAmount: '--', //hold
              masking: true,
            });
            this.props.onChange({ hold: undefined, available: undefined, investmentType: undefined }); //抛出投资类型
          } else if (hkType == '2') {
            // 港股通模式
            this.setState({
              hold: '--', //t+0
              available: '--', //t+2
              masking: true,
            });
            this.props.onChange({
              t0: undefined,
              t2: undefined,
              investmentType: undefined,
            });
          }
        }
      }
    }
  }
  //新接口 请求持仓
  getTradeHold = (datas) => {
    const { dispatch } = this.props;
    const { queryModel} = datas;
    this.setState({
      masking: false,
      loading: true,
    });
    if(queryModel=='old'){
      this.getTradeHoldOld(datas);
    }else{
      this.getTradeHoldNew(datas);
    }
  };
  getTradeHoldNew = (datas) => {
    const { dispatch } = this.props;
    const { portfolio, tradingcode, exchangecode, hkType, securityType } = datas;
    this.setState({
      masking: false,
      loading: true,
    });
    dispatch({
      type: 'tradeHoldM/queryAvailablePosition',
      payload: {
        tradingCode: tradingcode,
        exchangeCode: exchangecode,
        portfolioCode: portfolio,
        hkType: hkType,
        securityType: securityType,
      },
      callback: (data) => {
        if (hkType == '1') {
          // 默认模式
          if (data && !(parseFloat(data.availableAmount).toString() == 'NaN') && !(parseFloat(data.currentAmount).toString() == 'NaN')) {
            const { availableAmount, currentAmount } = data;
            this.props.onChange({ hold: currentAmount, available: availableAmount, investmentType: data.investmentType !== null ? data.investmentType : undefined });
            this.setState({
              availableAmount:  availableAmount ?? '--',
              currentAmount: currentAmount ?? '--',
              loading: false,
            });
          } else {
            this.props.onChange({ hold: undefined, available: undefined, investmentType: undefined });
            this.setState({
              availableAmount: '--',
              currentAmount: '--',
              loading: false,
            });
          }
        } 
      },
    });
  };
  //原接口请求持仓
  getTradeHoldOld = (datas) => {
    const { dispatch } = this.props;
    const { portfolio, tradingcode, exchangecode, hkType, securityType } = datas;
    this.setState({
      masking: false,
      loading: true,
    });
    dispatch({
      type: 'tradeHoldM/getPosition',
      payload: {
        tradingcode: tradingcode,
        exchangecode: exchangecode,
        fundId: portfolio,
        maatApi: this.props.maatApi,
        hkType: hkType,
        securityType: securityType,
      },
      callback: (data) => {
        if (hkType == '1') {
          // 默认模式
          if (data && !(parseFloat(data.availableAmount).toString() == 'NaN') && !(parseFloat(data.currentAmount).toString() == 'NaN')) {
            const { availableAmount, currentAmount } = data;
            this.props.onChange({ hold: currentAmount, available: availableAmount, investmentType: data.investmentType !== null ? data.investmentType : undefined });
            this.setState({
              availableAmount: availableAmount ? availableAmount : '--',
              currentAmount: currentAmount ? currentAmount : '--',
              loading: false,
            });
          } else {
            this.props.onChange({ hold: undefined, available: undefined, investmentType: undefined });
            this.setState({
              availableAmount: '--',
              currentAmount: '--',
              loading: false,
            });
          }
        } else if (hkType == '2') {
          // 港股通模式
          if (data && !(parseFloat(data.hold).toString() == 'NaN') && !(parseFloat(data.available).toString() == 'NaN')) {
            const { hold, available } = data;
            this.props.onChange({ t0: hold, t2: available, investmentType: data.investmentType !== null ? data.investmentType : undefined });
            this.setState({
              hold: hold ? hold : '--',
              available: available ? available : '--',
              loading: false,
            });
          } else {
            this.props.onChange({ t0: undefined, t2: undefined, investmentType: undefined });
            this.setState({
              hold: '--',
              available: '--',
              loading: false,
            });
          }
        } else if (hkType == '3') {
          // 股指期权模式
          if (data && data.dataSource) {
            data.dataSource.forEach((item, key) => {
              item.id = key;
            });
            this.setState({
              holdData: data.dataSource,
              loading: false,
            });
            this.props.onChange(data.dataSource);
          } else {
            this.setState({
              holdData: [],
              loading: false,
            });
            this.props.onChange([]);
          }
        }
      },
    });
  };
  //根据productGroupId（产品组id）获取数据
  getDataByProductGroupId = (datas) => {
    const { dispatch } = this.props;
    const { productGroupId, tradingcode, exchangecode, securityType } = datas;
    this.setState({
      masking: false,
      loading: true,
    });
    dispatch({
      type: 'tradeHoldM/getPositionByProductGroupId',
      payload: {
        tradingCode: tradingcode,
        exchangeCode: exchangecode,
        groupId: productGroupId,
        securityType: securityType,
      },
      callback: (data) => {
        if (data && !(parseFloat(data.tzeroAvailableFund).toString() == 'NaN') && !(parseFloat(data.toneAvailableFund).toString() == 'NaN')) {
          const { tzeroAvailableFund, toneAvailableFund } = data;
          this.props.onChange({ hold: toneAvailableFund, available: tzeroAvailableFund, investmentType: data.investmentType !== null ? data.investmentType : undefined });
          this.setState({
            availableAmount: tzeroAvailableFund ? tzeroAvailableFund : '--',
            currentAmount: toneAvailableFund ? tzeroAvailableFund : '--',
            loading: false,
          });
        } else {
          this.props.onChange({ hold: undefined, available: undefined, investmentType: undefined });
          this.setState({
            availableAmount: '--',
            currentAmount: '--',
            loading: false,
          });
        }
      },
    });
  };
  //千分位数据处理
  thousandsFormat = (number) => {
    return fixedNum(number, 2);
  };
  renderTable() {
    const { holdData } = this.state;
    const {
      globalM: {
        dataDictionary: { MAAT_FUT_STOCKTYPE = [] },
      },
    } = this.props;
    const columns = [
      {
        title: '合约代码',
        key: 'tradingCode',
      },
      {
        title: '多空标志',
        key: 'stockType',
        render: (text) => {
          return findValueByCode(text, MAAT_FUT_STOCKTYPE);
        },
      },
      {
        title: '持仓数量(手)',
        key: 'holdNum',
        type: 'number',
      },
      {
        title: '加权成本价(元)',
        key: 'price',
        type: 'money',
      },
    ];
    return (
      <div style={{ position: 'relative' }}>
        <TableC
          columns={columns}
          dataSource={holdData}
          loading={this.state.loading == true}
          hidePage={true}
          rowKey='id'
          scroll={{ y: 320 }}
          onRow={(record) => {
            return {
              onDoubleClick: (event) => {
                this.props.codeChangeInfo(record);
              }, // 双击行抛出数据
            };
          }}
        />
        {this.state.masking ? <NoDataMaskC height={'100%'} title={'请选择相对应组合，加载数据！'} /> : null}
      </div>
    );
  }

  render() {
    const { width, type, hkType } = this.props;
    const { currentAmount, availableAmount, masking, loading, hold, available } = this.state;
    const leftContent = () => {
      return (
        <div className={myStyle.rightInfo}>
          <IconC type='info' />
          <span>双击持仓可回填指令</span>
        </div>
      );
    };
    return (
      <div style={{ width }}>
        {this.props.hasHeader ? (
          <div>
            <FirstHeaderC title={'持仓'} Right={hkType != 3 ? undefined : leftContent()} />
          </div>
        ) : (
          ''
        )}
        {hkType != 3 ? (
          <Spin spinning={loading == true}>
            <div className={myStyle.fundsContainer}>
              <div className={myStyle.showLeft}>
                <span className={myStyle.title}>持仓数量</span>
                {hkType == '2' ? (
                  <span className={myStyle.pointFont}>{masking ? 'xxxxx' : hold == '--' ? hold : this.thousandsFormat(hold)}</span>
                ) : (
                  <span className={myStyle.pointFont}>{masking ? 'xxxxx' : currentAmount == '--' ? currentAmount : this.thousandsFormat(currentAmount)}</span>
                )}
              </div>
              <div className={myStyle.showRight}>
                <span className={myStyle.title}>可用数量</span>
                {hkType == '2' ? (
                  <span className={myStyle.pointFont}>{masking ? 'xxxxx' : available == '--' ? available : this.thousandsFormat(available)}</span>
                ) : (
                  <span className={myStyle.pointFont}>{masking ? 'xxxxx' : availableAmount == '--' ? availableAmount : this.thousandsFormat(availableAmount)}</span>
                )}
              </div>
              {masking ? <NoDataMaskC height={'50px'} title={type == '12' ? '请选择产品组,证券代码，加载数据！' : '请选择组合,证券代码，加载数据！'} /> : null}
            </div>
          </Spin>
        ) : (
          this.renderTable()
        )}
      </div>
    );
  }
}

// props默认值
TradeHoldC.propsTypes = {
  type: PropTypes.number | PropTypes.string, // 类型，type=12：是根据产品组id获取的资金可用,其他为 根据组合id获取的资金可用
  hkType: PropTypes.number | PropTypes.string, // hkType=1(默认模式：持仓数量和可用数量模式) hkType=2(港股通模式：T+0可用和T+2可用模式)
  securityType: PropTypes.string, // 证券类别,是用来给后台确认返回的是哪一类的持仓
  productGroupId: PropTypes.string, // 产品组id
  portfolio: PropTypes.string, // 组合id
  tradingcode: PropTypes.string, // 证券代码
  exchangecode: PropTypes.string, // 交易所代码
  onChange: PropTypes.func, // 抛出事件({hold:xx,available:xx})
  width: PropTypes.string, // 组件宽
  timeStamp: PropTypes.number | PropTypes.string, // 时间戳
  hasHeader: PropTypes.bool, //标题是否展示
  maatApi: PropTypes.bool, // 正常情况下，在哪个环境下，就访问哪个环境的产品，
  // 但在投资建议书模块中，被引用到资管环境时，该组件的接口仍然要访问maat环境中的产品（而不是资管环境中产品），此时需要在接口前添加maat前缀
};
export default connect(({ tradeHoldM, loading, globalM }) => ({
  tradeHoldM,
  loading,
  globalM,
}))(TradeHoldC);
